package com.example.gokuplayalong.bases.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.example.gokuplayalong.bases.alipay.util.OrderInfoUtil2_0;
import com.example.gokuplayalong.bases.base.AppParams;
import com.example.gokuplayalong.bases.base.ExceptionHandler;
import com.example.gokuplayalong.bases.base.Tools;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class AlipayWork {
    static String APPID = "2021005116652932";
    static String PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDMD45rfzsLqMwmfqjADPOWdcInFU7wZCcY6F/EbwgzlOph1JOuay7zMFSiasFA8F8OCjwKNEbJOIVEfsKSsW0V33UdVY0OiaP9W0MPja+Wn84DnN5VkDOxhd82fEdeA492598NgefJedd9AF7msBoZUwEUBMRh0zQ8V+ZiMLP0WgXcZBXG7qIc3Ec3NxTldw1/U7EMkRMcEe+mVsZNRAWmZpqNzb9pLeuvmH7vXA/ByperlC+HFfWlhLCp7fSGALDHtStauuWHe4ASy5Zv/RLS5AuFTGCp1tOao1S/l8Ew40kMFP7VhA2Gm2MpZML6oYiqnplZX1Jz9eW76P58/fmLAgMBAAECggEAJKBKLMs6Wt5iPiqPuWDZu9DJF2DAuW8QgWz7+3L+YtvAseyI0U6Vr7qmBjzpEPHT7d4yZpZ5ehZ1/RRPcir8bGeeSrSXS9uynn/p6nnA4WUvggB++5aVYLCpnsrxuFMlRe9aXr9JTiVbYylU300Ocisuz1wHr5NMFeSlCky5kArh7FBmL7G8pU+ODJh8/Q+lbnC+KT4xiu9ThDYvMDn5WiMezRKMK21keSnz897hypBTXCsTJBoss03YlLMREQPcpPbFkBnlrTZ7t4A9sUC8E5qbpVprqko/MdVWMQQmBbm+ATgbsOA1pe78ZuzYX1MVNCBGgaUmKFeAOPs7fqHzUQKBgQD+T+NG4iLW0c7YNytLNpSEDL5/rRVnx1zjr59vTRVZeNZbcB4w8PTygfS8S1wneYbzhOqeB4vyGtrCDfkm4vjlH1sNFInyHlhFzhPI6CD3SoWrnoQOUIUt+Th+5RT07bUDRugvquOcbHcrOPtWNoSe6F+nZWqVfyJyXEro9lXM4wKBgQDNakjSjEPlxyRBXAyJbSV4OyXywryzxa6/Uu7keVsk1JtvJJ7hc/z/Cs8ycRlmPNuX3ajHNLBSP6Jh/E82ZyPKVXgH+D9RwGeFnOGmMaWKRyxQXQrDoeamFfgfCQ4POvsts3UWLhbX/sV557kSUI/8NZoY45Nq5gjSy2D2eREpOQKBgQCuXA2CeubSDDVaDrEzNy+qPaaamQv1BD4OqUmRoPMDThMBzCQXAA2g+zLVqoF7WxoIelf1k00C6CCWLchmPfXR+aaOmEdf5ig1a+4qr+RyR/jPyrXVrqUw+Q8gCWZN63BQ19u3Wt4FUGSAEOhZmrVg0gdLGQBzkSAH8nk1sjbvawKBgQCMbLYvyVe5QzQTwluHryfIU5cTp/DcbK2TeZx6cEPQn89KYZyDv4kayUbv0sVsUPpFjXCODgTjlUDq/1Mfe87JyTfvKtQOjRu4CZFwzcu/BfzTS2fKaWmF7MrcXJJR8x43FdFbQlK3giF5vuGUFaL45aPck+b5UxyBDivREt6acQKBgCGWpDcvWsyEGxNmulvFez2u6uO9U1TIyuio0az+TU8tNzPOIKqjvu3ETO/011jaD++S2nXKsHTcyBFvbpeKXI5QR5a8nFIfZXM5q041z4GQckxYtS6QMelAVJFd4wwBFBmI6PxVExdTxrOaANvc2j/APTiXCuxk3kPGvGjlumYV";


    public static String buildOrderInfo(double total_amount, String product_name) {

        //Logger.d("buildOrderInfo","金额 : " + total_amount + " 商品名称 : " + product_name);
        if (total_amount < 0.01) total_amount = 0.01;
        if (product_name == null || product_name.equals("")) product_name = "默认";

        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, total_amount, product_name);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String sign = OrderInfoUtil2_0.getSign(params, PRIVATE_KEY, true);
        final String orderInfo = orderParam + "&" + sign;


        return orderInfo;
    }

    public static String getTime() {
        long time = System.currentTimeMillis();//long now = android.os.SystemClock.uptimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1 = new Date(time);
        return format.format(d1);
    }

    public static String rechargeAlipay(JSONObject bean) {
        String orderStr = "";
        try {
            AlipayConfig alipayConfig = new AlipayConfig();
            alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
            alipayConfig.setAppId(APPID);
            alipayConfig.setPrivateKey(PRIVATE_KEY);

            //设置应用公钥证书路径
            alipayConfig.setAppCertPath(AppParams.getInstance().crtsPathLinux + "/appCertPublicKey_2021005116652932.crt");
            //设置支付宝公钥证书路径
            alipayConfig.setAlipayPublicCertPath(AppParams.getInstance().crtsPathLinux + "/alipayCertPublicKey_RSA2.crt");
            //设置支付宝根证书路径
            alipayConfig.setRootCertPath(AppParams.getInstance().crtsPathLinux + "/alipayRootCert.crt");

            alipayConfig.setFormat("json");
            alipayConfig.setCharset("UTF-8");
            alipayConfig.setSignType("RSA2");


            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);

            // 构造请求参数以调用接口
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();

            // 设置商户订单号
            model.setOutTradeNo(bean.getString("out_trade_no"));

            request.setNotifyUrl("http://47.121.179.98:8085/public/client/alipayCallback");

            model.setBody("{\"phone\":\"" + bean.getString("phone") + "\"}");
            // 设置订单总金额
            model.setTotalAmount(bean.getString("total_amount"));

            // 设置订单标题
            model.setSubject("代练客充值");

            // 设置产品码
            model.setProductCode("QUICK_MSECURITY_PAY");


            request.setBizModel(model);

            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            orderStr = response.getBody();

            if (response.isSuccess()) {
                System.out.println("调用成功");
            }
            else {
                System.out.println("调用失败");
                // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
                // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
                // System.out.println(diagnosisUrl);
            }
        } catch (Throwable e) {
            ExceptionHandler.saveException(Thread.currentThread().getStackTrace()[1].getClassName() + Thread.currentThread().getStackTrace()[1].getMethodName() + Thread.currentThread().getStackTrace()[1].getLineNumber(), e);

        }
        return orderStr;
    }


    public static int payoutAlipay(JSONObject bean) {
        try {
            AlipayConfig alipayConfig = new AlipayConfig();
            alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
            alipayConfig.setAppId(APPID);
            alipayConfig.setPrivateKey(PRIVATE_KEY);

            //设置应用公钥证书路径
            alipayConfig.setAppCertPath(AppParams.getInstance().crtsPathLinux + "/appCertPublicKey_2021005116652932.crt");
            //设置支付宝公钥证书路径
            alipayConfig.setAlipayPublicCertPath(AppParams.getInstance().crtsPathLinux + "/alipayCertPublicKey_RSA2.crt");
            //设置支付宝根证书路径
            alipayConfig.setRootCertPath(AppParams.getInstance().crtsPathLinux + "/alipayRootCert.crt");


            alipayConfig.setFormat("json");
            alipayConfig.setCharset("UTF-8");
            alipayConfig.setSignType("RSA2");

            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);

            // 构造请求参数以调用接口
            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();

            // 设置商家侧唯一订单号
            model.setOutBizNo(bean.getString("out_trade_no"));

            // 设置订单总金额
            model.setTransAmount(String.valueOf(Math.abs(Tools.doubleFormat(bean.getDoubleValue("var")))));

            // 设置描述特定的业务场景
            model.setBizScene("DIRECT_TRANSFER");

            // 设置业务产品码
            model.setProductCode("TRANS_ACCOUNT_NO_PWD");

            // 设置转账业务的标题
            model.setOrderTitle("代练客提现");

            // 设置收款方信息
            Participant payeeInfo = new Participant();
            payeeInfo.setIdentity(bean.getString("alipayid"));
            payeeInfo.setName(bean.getString("realname"));
            payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
            model.setPayeeInfo(payeeInfo);

            // 设置业务备注
            model.setRemark(bean.getString("phone"));

            // 设置转账业务请求的扩展参数
            model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");

            request.setBizModel(model);

            AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
            System.out.println(response.getBody());

            if (response.isSuccess()) {
                System.out.println("调用成功");
                return 1;
            }
            else {
                System.out.println("调用失败");
                bean.put("response", response.getSubMsg());
                // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
                // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
                // System.out.println(diagnosisUrl);
                return 0;
            }

        } catch (Throwable e) {
            ExceptionHandler.saveException(Thread.currentThread().getStackTrace()[1].getClassName() + Thread.currentThread().getStackTrace()[1].getMethodName() + Thread.currentThread().getStackTrace()[1].getLineNumber(), e);
            return 0;

        }
    }

    public static int rechargeBack(JSONObject bean) {
        try {

            AlipayConfig alipayConfig = new AlipayConfig();
            alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
            alipayConfig.setAppId(APPID);
            alipayConfig.setPrivateKey(PRIVATE_KEY);

            //设置应用公钥证书路径
            alipayConfig.setAppCertPath(AppParams.getInstance().crtsPathLinux + "/appCertPublicKey_2021005116652932.crt");
            //设置支付宝公钥证书路径
            alipayConfig.setAlipayPublicCertPath(AppParams.getInstance().crtsPathLinux + "/alipayCertPublicKey_RSA2.crt");
            //设置支付宝根证书路径
            alipayConfig.setRootCertPath(AppParams.getInstance().crtsPathLinux + "/alipayRootCert.crt");

            alipayConfig.setFormat("json");
            alipayConfig.setCharset("UTF-8");
            alipayConfig.setSignType("RSA2");

            // 初始化SDK
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);

            // 构造请求参数以调用接口
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            AlipayTradeRefundModel model = new AlipayTradeRefundModel();

            // 设置商户订单号
            model.setOutTradeNo(bean.getString("out_trade_no"));

            // 设置退款金额
            model.setRefundAmount(String.valueOf(bean.getDoubleValue("total_amount")));

            // 设置退款原因说明
            model.setRefundReason("正常退款");

            // 设置退款请求号
            model.setOutRequestNo("HZ01RF001");


            request.setBizModel(model);
            // 第三方代调用模式下请设置app_auth_token
            // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

            AlipayTradeRefundResponse response = alipayClient.certificateExecute(request);
            System.out.println(response.getBody());

            if (response.isSuccess()) {
                System.out.println("调用成功");
                return 1;
            }
            else {
                System.out.println("调用失败");
                // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
                // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
                // System.out.println(diagnosisUrl);
                bean.put("response", response.getSubMsg());


                return 0;
            }
        } catch (Throwable e) {
            return 0;
        }

    }
}
